package com.shigu.component.shiro.filter;


import com.shigu.agent.enums.UserRoleType;
import com.shigu.mo.services.OverallSituationService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 商户过滤器
 */
@Service("business_filter")
public class BusinessFilter extends UserLoginFilter{

    @Autowired
    private OverallSituationService overallSituationService;

    @Value("${main_host}")
    private String MAIN_HOST;

    private final String loginUrl="wappage/buspage/login";

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        String url=((HttpServletRequest)request).getRequestURL().toString();
        if (url.endsWith(".json")&&!overallSituationService.getOpenProgram()) {
            super.writeToResponse((HttpServletResponse) response,"{\"success\":false,\"msg\":\"服务器维护中，请稍候再试\"}");
            return;
        }
        if (hasLogin(MAIN_HOST+loginUrl,(HttpServletRequest) request,(HttpServletResponse) response)) {
            Subject currentUser=SecurityUtils.getSubject();
            if(currentUser.hasRole(UserRoleType.BUSINESS.getValue())){
                chain.doFilter(request,response);
            }else{
                redirectToUrl(MAIN_HOST+loginUrl,(HttpServletRequest)request,(HttpServletResponse)response);
            }
        }
    }
}
